var Imap = require('imap')
var MailParser = require("mailparser").MailParser
var fs = require("fs")

var imap = new Imap({
  user: '#####',
  password: '####',
  host: 'imap.infohold.com.cn',
  port: 993,
  tls: true,
  tlsOptions: { rejectUnauthorized: false },
  debug: (log) => {
    console.log(log)
  }
});

function openInbox(cb) {
  imap.openBox('INBOX', true, cb);
}

var messages = []

imap.once('ready', function () {
  openInbox(function (err, box) {
    console.log("open")
    if (err) throw err;
    imap.search(['ALL'], function (err, results) {
      debugger
      if (err) throw err;
      var f = imap.fetch(results, { bodies: '' });

      f.on('message', function (msg, seqno) {
        var mailparser = new MailParser()
        msg.on('body', function (stream, info) {
          stream.pipe(mailparser);
          mailparser.on("headers", function (headers) {
            console.log("邮件主题: " + headers.get('subject'));
            console.log("发件人: " + headers.get('from').text);
            console.log("收件人: " + headers.get('to').text);
            console.log('发件时间：' + headers.get('date'));
          });
          mailparser.on("data", function (data) {
            //data是对象
            if (data.type === 'text') {
              console.log("邮件内容: " + data.html);
            }
            if (data.type === 'attachment') {
              console.log("附件名称:" + data.filename);
              data.content.pipe(fs.createWriteStream(data.filename));

              //保存附件到当前目录下
              data.release();
            }
          });
        });
        msg.once('end', function () {
          console.log(seqno + 'Finished');
        });
      });
      f.once('error', function (err) {
        console.log('Fetch error: ' + err);
      });
      f.once('end', function () {
        console.log('Done fetching all messages!');
        imap.end();
      });
    });
  });
});

imap.once('error', function (err) {
  console.log(err);
});

imap.once('end', function () {
  console.log('Connection ended');
});

imap.connect();